<template>
  <div class="patrol-sign">
    <!-- 查询区域 -->
    <div class="search-bar">
      <el-input v-model="searchPointName" placeholder="签到点名称" style="width: 200px; margin-right: 10px;" />
      <el-input v-model="searchInspectorName" placeholder="巡查人" style="width: 200px; margin-right: 10px;" />
      <el-button type="primary" @click="handleSearch">查询</el-button>
      <el-button @click="handleReset">重置</el-button>
      <el-button type="primary" style="float: right;" @click="handleAdd">+ 添加签到点</el-button>
    </div>


    <el-table :data="tableData" :loading="loading" style="width: 100%;">
      <template #empty>
        <div>自定义无数据内容，tableData长度：{{ tableData.length }}</div>
      </template>
      <el-table-column label="分类">
        <template #default="scope">
          {{ scope.row.categoryName }}
        </template>
      </el-table-column>
      <el-table-column prop="pointName" label="签到点名称" />
      <el-table-column prop="inspectorNames" label="巡查人" />
      <el-table-column prop="location" label="位置" />
      <el-table-column prop="description" label="说明" />
      <el-table-column label="操作" width="150">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.row)" style="margin-left: 8px;">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-model:current-page="currentPage"
      :page-size="pageSize"
      :total="total"
      layout="prev, pager, next, jumper"
      style="margin-top: 20px; text-align: right;"
    />

    <!-- 编辑/新增弹窗 -->
    <el-dialog v-model="editDialogVisible" :title="editForm.id ? '编辑签到点' : '添加签到点'" width="600px">
      <el-form :model="editForm" label-width="100px">
        <el-form-item label="所属分类">
          <el-select v-model="editForm.categoryLevel1Id" placeholder="请选择一级分类" style="width: 45%; margin-right: 10px;" @change="onCategoryLevel1Change">
            <el-option v-for="item in categoryLevel1List" :key="item.id" :label="item.categoryName" :value="item.id" />
          </el-select>
          <el-select v-model="editForm.categoryId" placeholder="请选择二级分类" style="width: 45%;">
            <el-option v-for="item in categoryLevel2List" :key="item.id" :label="item.categoryName" :value="Number(item.id)" />
          </el-select>
        </el-form-item>
        <el-form-item label="签到点名称">
          <el-input v-model="editForm.pointName" placeholder="请输入签到点名称" />
        </el-form-item>
        <el-form-item label="巡查人">
          <el-input
            v-model="editForm.inspectorNames"
            placeholder="请选择巡查人"
            readonly
            @click="showInspectorDialog = true"
          />
        </el-form-item>
        <el-form-item label="地图位置">
          <el-input v-model="editForm.location" placeholder="请选择地图位置" readonly @click="showMapDialog = true" />
        </el-form-item>
        <el-form-item label="说明">
          <el-input v-model="editForm.description" type="textarea" placeholder="请输入说明" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleEditConfirm">确定</el-button>
      </template>
    </el-dialog>

    <!-- 选择巡查人弹窗 -->
    <el-dialog v-model="showInspectorDialog" title="选择巡查人" width="700px">
      <div style="margin-bottom: 10px; display: flex; gap: 10px;">
        <el-input v-model="inspectorSearch.realName" placeholder="真实姓名" style="width: 180px;" />
        <el-input v-model="inspectorSearch.phone" placeholder="手机号" style="width: 180px;" />
        <el-button type="primary" @click="handleInspectorQuery">查询</el-button>
      </div>
      <div style="margin-bottom: 10px; color: #409EFF;">
        已选择 {{ selectedInspectors.length }} 人
      </div>
      <el-table ref="inspectorTableRef" :data="inspectorList" @selection-change="handleInspectorSelect" row-key="id" style="width: 100%;">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="realName" label="真实姓名" />
        <el-table-column prop="phone" label="手机号" />
        <el-table-column prop="departmentName" label="所属部门" />
      </el-table>
      <template #footer>
        <el-button @click="showInspectorDialog = false">取消</el-button>
        <el-button type="primary" @click="confirmInspectorSelect">确定</el-button>
      </template>
    </el-dialog>

    <!-- 选择地图弹窗 -->
    <el-dialog v-model="showMapDialog" title="选择地图位置" width="800px">
      <div style="margin-bottom: 10px; display: flex; gap: 10px; align-items: center;">
        <el-input v-model="schoolSearchName" placeholder="请输入学校全称或具体校区名称" style="width: 300px;" />
        <el-button type="primary" @click="searchSchoolOnMap">搜索</el-button>
        <el-button type="success" circle @click="locateMyPosition" :title="'定位到我的位置'">
          <svg viewBox="0 0 24 24" width="20" height="20" fill="none" xmlns="http://www.w3.org/2000/svg">
            <circle cx="12" cy="12" r="7" stroke="#409EFF" stroke-width="2"/>
            <circle cx="12" cy="12" r="2" fill="#409EFF"/>
            <line x1="12" y1="2" x2="12" y2="5" stroke="#409EFF" stroke-width="2"/>
            <line x1="12" y1="19" x2="12" y2="22" stroke="#409EFF" stroke-width="2"/>
            <line x1="2" y1="12" x2="5" y2="12" stroke="#409EFF" stroke-width="2"/>
            <line x1="19" y1="12" x2="22" y2="12" stroke="#409EFF" stroke-width="2"/>
          </svg>
        </el-button>
      </div>
      <div style="color: #999; margin-bottom: 10px; font-size: 13px;">建议输入学校全称或具体校区名称，以获得更精准定位，或直接定位到我的位置</div>
      <div id="tmap-container" style="height:400px;width:100%"></div>
      <template #footer>
        <el-button @click="showMapDialog = false">取消</el-button>
        <el-button type="primary" @click="confirmMapSelect">确定</el-button>
      </template>
    </el-dialog>

    <!-- 删除弹窗 -->
    <el-dialog v-model="deleteDialogVisible" title="删除" width="400px">
      <div>您确定要删除"{{ deleteRow?.pointName }}"签到点吗？</div>
      <template #footer>
        <el-button @click="deleteDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleDeleteConfirm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
console.log('PatrolSign 加载了');
import { ref, onMounted, computed, watch, nextTick } from 'vue'
import { fetchSignList, addSign, updateSign, deleteSign } from '@/api/safetySign'
import { fetchCategoryLevel1, fetchCategoryLevel2 } from '@/api/safetyCategory'
import { fetchSecurityGuardUserList } from '@/api/securityGuardUser'

const searchPointName = ref('')
const searchInspectorName = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const tableData = ref([])
const loading = ref(false)

const editDialogVisible = ref(false)
const deleteDialogVisible = ref(false)
const showInspectorDialog = ref(false)
const showMapDialog = ref(false)
const inspectorList = ref([])
const selectedInspectors = ref([])

const editForm = ref({
  id: null,
  categoryLevel1Id: null,
  categoryId: null,
  pointName: '',
  inspectorNames: '',
  location: '',
  description: '',
  inspectorIds: []
})
const deleteRow = ref(null)

const inspectorSearch = ref({ realName: '', phone: '' })

const categoryLevel1List = ref([])
const categoryLevel2List = ref([])

const schoolSearchName = ref('')
let tmap = null
let marker = null

const inspectorTableRef = ref(null)

watch(showMapDialog, async (val) => {
  if (val) {
    await loadTencentMapScript()
    setTimeout(() => {
      if (!tmap) {
        tmap = new window.TMap.Map('tmap-container', {
          center: new window.TMap.LatLng(39.90923, 116.397428), // 默认北京
          zoom: 15
        })
      }
    }, 300)
  }
})

// 修改数据加载函数
const fetchData = async () => {
  console.log('fetchData called')
  loading.value = true
  try {
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      pointName: searchPointName.value,
      inspectorName: searchInspectorName.value
    }
    const res = await fetchSignList(params)
    tableData.value = res.data?.records || []
    total.value = res.data?.total || 0
    console.log('tableData after fetch:', tableData.value)
  } finally {
    loading.value = false
  }
}

function handleSearch() {
  currentPage.value = 1
  fetchData()
}
function handleReset() {
  searchPointName.value = ''
  searchInspectorName.value = ''
  currentPage.value = 1
  fetchData()
}
function handleAdd() {
  editForm.value = {
    id: null,
    categoryLevel1Id: null,
    categoryId: null,
    pointName: '',
    inspectorNames: '',
    location: '',
    description: '',
    inspectorIds: []
  }
  categoryLevel2List.value = []
  selectedInspectors.value = []
  editDialogVisible.value = true
}
async function handleEdit(row) {
  // 优先用row.parentCategoryId，保证所属分类回显
  editForm.value.categoryLevel1Id = Number(row.parentCategoryId)
  await onCategoryLevel1Change(editForm.value.categoryLevel1Id)
  editForm.value.categoryId = Number(row.categoryId)
  editForm.value.id = row.id
  editForm.value.pointName = row.pointName
  editForm.value.inspectorIds = Array.isArray(row.inspectorIds)
    ? row.inspectorIds.map(Number)
    : (row.inspectorIds ? String(row.inspectorIds).split(',').map(id => Number(id)) : [])
  editForm.value.inspectorNames = row.inspectorNames || ''
  editForm.value.location = row.location
  editForm.value.description = row.description
  selectedInspectors.value = inspectorList.value.filter(user =>
    editForm.value.inspectorIds.includes(user.id)
  )
  editDialogVisible.value = true
}

// 弹窗打开时自动回显已选巡查人
watch(showInspectorDialog, async (val) => {
  if (val && editForm.value.inspectorIds) {
    selectedInspectors.value = inspectorList.value.filter(user =>
      editForm.value.inspectorIds.includes(user.id)
    )
    await nextTick()
    inspectorList.value.forEach(row => {
      inspectorTableRef.value && inspectorTableRef.value.toggleRowSelection(row, editForm.value.inspectorIds.includes(row.id))
    })
    console.log('弹窗打开时selectedInspectors:', selectedInspectors.value)
    console.log('当前inspectorList:', inspectorList.value)
    console.log('当前editForm.inspectorIds:', editForm.value.inspectorIds)
  }
})

async function handleEditConfirm() {
  loading.value = true
  try {
    const params = {
      id: editForm.value.id,
      categoryId: editForm.value.categoryId,
      pointName: editForm.value.pointName,
      location: editForm.value.location,
      inspectorIds: editForm.value.inspectorIds,
      description: editForm.value.description
    }
    if (editForm.value.id) {
      await updateSign(params)
      window.$message.success('编辑成功')
    } else {
      await addSign(params)
      window.$message.success('添加成功')
    }
  } catch (e) {
    window.$message.error('操作失败，请检查网络或联系管理员')
    console.error('handleEditConfirm error:', e)
  } finally {
    loading.value = false
    await fetchData()
    editDialogVisible.value = false
  }
}
function handleDelete(row) {
  deleteRow.value = row
  deleteDialogVisible.value = true
}
async function handleDeleteConfirm() {
  loading.value = true
  try {
    await deleteSign({ id: deleteRow.value.id })
    window.$message.success('删除成功')
  } catch (e) {
    window.$message.error('删除失败，请检查网络或联系管理员')
    console.error('handleDeleteConfirm error:', e)
  } finally {
    loading.value = false
    await fetchData()
    deleteDialogVisible.value = false
  }
}
function handleInspectorSelect(val) {
  selectedInspectors.value = val
  console.log('多选变化selectedInspectors:', selectedInspectors.value)
}
function confirmInspectorSelect() {
  editForm.value.inspectorIds = selectedInspectors.value.map(i => i.id)
  editForm.value.inspectorNames = selectedInspectors.value.map(i => i.realName).join(', ')
  showInspectorDialog.value = false
}
function confirmMapSelect() {
  editForm.value.location = '保定理工学院'
  showMapDialog.value = false
}
async function handleInspectorQuery() {
  const res = await fetchSecurityGuardUserList(inspectorSearch.value)
  if (Array.isArray(res.data)) {
    inspectorList.value = res.data
  } else if (Array.isArray(res.data?.data)) {
    inspectorList.value = res.data.data
  }
}

// 动态加载腾讯地图JS API
function loadTencentMapScript() {
  return new Promise((resolve, reject) => {
    if (window.TMap) {
      resolve()
      return
    }
    const script = document.createElement('script')
    script.type = 'text/javascript'
    script.src = 'https://map.qq.com/api/gljs?v=1.exp&key=UEXBZ-Z2ICJ-S6IFH-XKPBM-WXN5K-PJBX5'
    script.onload = resolve
    script.onerror = reject
    document.head.appendChild(script)
  })
}

function searchSchoolOnMap() {
  if (!schoolSearchName.value) {
    window.$message?.warning?.('请输入学校名称')
    return
  }
  fetch(`https://apis.map.qq.com/ws/geocoder/v1/?address=${encodeURIComponent(schoolSearchName.value)}&key=UEXBZ-Z2ICJ-S6IFH-XKPBM-WXN5K-PJBX5`)
    .then(res => res.json())
    .then(data => {
      if (data.status === 0 && data.result && data.result.location) {
        const { lat, lng } = data.result.location
        const latlng = new window.TMap.LatLng(lat, lng)
        tmap.setCenter(latlng)
        tmap.setZoom(18)
        if (marker) {
          marker.setMap(null)
        }
        marker = new window.TMap.MultiMarker({
          map: tmap,
          geometries: [{
            id: 'school',
            styleId: 'marker',
            position: latlng,
            properties: {
              title: schoolSearchName.value
            }
          }]
        })
      } else {
        window.$message?.error?.('未找到该学校，请检查名称')
      }
    })
}

function locateMyPosition() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(
      (position) => {
        const { latitude, longitude } = position.coords
        const latlng = new window.TMap.LatLng(latitude, longitude)
        tmap.setCenter(latlng)
        tmap.setZoom(18)
        if (marker) {
          marker.setMap(null)
        }
        marker = new window.TMap.MultiMarker({
          map: tmap,
          geometries: [{
            id: 'myPosition',
            styleId: 'marker',
            position: latlng,
            properties: {
              title: '我的位置'
            }
          }]
        })
        // 使用腾讯地图逆地址解析获取位置描述
        new window.TMap.service.Geocoder().getAddress(latlng).then(result => {
          if (result.status === 0) {
            editForm.value.location = result.result.address
            window.$message?.success?.(`已定位到：${result.result.address}`)
          }
        })
      },
      (error) => {
        window.$message?.error?.(`定位失败：${error.message}`)
      }
    )
  } else {
    window.$message?.error?.('您的浏览器不支持地理定位')
  }
}

async function onCategoryLevel1Change(level1Id) {
  // 只在level1Id为有效数字时才传parentId
  const params = {};
  if (
    level1Id !== null &&
    level1Id !== undefined &&
    level1Id !== '' &&
    !isNaN(Number(level1Id))
  ) {
    params.parentId = Number(level1Id);
  }
  const res = await fetchCategoryLevel2(params)
  if (Array.isArray(res.data?.records)) {
    categoryLevel2List.value = res.data.records
  } else if (Array.isArray(res.data?.data?.records)) {
    categoryLevel2List.value = res.data.data.records
  }
  editForm.value.categoryId = null
  console.log('二级分类列表:', categoryLevel2List.value)
}

onMounted(async () => {
  // 1. 加载分类数据
  const res1 = await fetchCategoryLevel1({ level: 1 })
  if (Array.isArray(res1.data?.records)) {
    categoryLevel1List.value = res1.data.records
  } else if (Array.isArray(res1.data?.data?.records)) {
    categoryLevel1List.value = res1.data.data.records
  }
  console.log('一级分类列表:', categoryLevel1List.value)

  // 2. 加载巡查人数据
  const userRes = await fetchSecurityGuardUserList()
  if (Array.isArray(userRes.data)) {
    inspectorList.value = userRes.data
  } else if (Array.isArray(userRes.data?.data)) {
    inspectorList.value = userRes.data.data
  }

  // 3. 加载表格数据
  await fetchData()
})

// 打印表格数据，便于调试
watch(tableData, (val) => {
  console.log('tableData', val)
})
</script>

<style scoped>
.patrol-sign {
  background: #fff;
  padding: 24px;
  border-radius: 8px;
}
.search-bar {
  margin-bottom: 10px;
  display: flex;
  align-items: center;
}
</style>
